package adv.i31.robot;

import java.util.ArrayList;

import android.opengl.GLES20;
import android.opengl.Matrix;

public class Robot implements IDrawableObject {

	private VertexBuffer mVertexBuffer;

	private float[] mMVPMatrix = new float[16];

	private float[] mModelMatrix = new float[16];

	ArrayList<Joint> mJoints = new ArrayList<Joint>();

	public Robot() {
		// initialize the vertex buffer
		mVertexBuffer = new VertexBuffer(new float[] {
				// X, Y, Z
				-1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f,
				-1.0f, 0.0f,

				1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f });

		Matrix.setIdentityM(mModelMatrix, 0);

		// Matrix.scaleM(mModelMatrix, 0, 0.5f, 0.5f, 0.5f);

		Joint previousJoint = null;
		Joint newJoint = null;
		for (int i = 0; i < 10; i++) {
			newJoint = new Joint();
			newJoint.mPreviousJoint = previousJoint;
			newJoint.mAngle = (float) Math.random() * 180.0f - 90.0f;
			newJoint.mLength = (float) Math.random() * 2.0f + 1.0f;
			mJoints.add(newJoint);
			previousJoint = newJoint;
		}
		// calculate the matrices
		mJoints.get(9).calculateTransformation();
	}

	public void draw(Program p, Camera c) {

		GLES20.glVertexAttribPointer(p.getmPositionHandle(), mVertexBuffer.getmPositionDataSize(),
				GLES20.GL_FLOAT, false, mVertexBuffer.getmStrideBytes(),
				mVertexBuffer.getmFloatBuffer());

		GLES20.glEnableVertexAttribArray(p.getmPositionHandle());

		// Matrix.multiplyMM(mMVPMatrix, 0, c.getmViewMatrix(), 0, mModelMatrix,
		// 0);

		// calculate Model-View-Projection Matrix
		Matrix.multiplyMM(mMVPMatrix, 0, c.getmProjMatrix(), 0, c.getmViewMatrix(), 0);

		// Pass the MVP Matrix to the shader
		GLES20.glUniformMatrix4fv(p.getmMVPMatrixHandle(), 1, false, mMVPMatrix, 0);

		// GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);
		// GLES20.glDrawArrays(GLES20.GL_POINTS, 0, 3);
		GLES20.glDrawArrays(GLES20.GL_LINE_STRIP, 0, mVertexBuffer.getNumVertices());

		for (Joint j : mJoints) {
			j.draw(p, c);
		}
	}
}
